package cn.itsource.basic.controller;


import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件处理接口类
 * 文件上传
 * 文件下载 - 不要
 * 文件删除
 * 文件访问 - 不要 - http://123.207.27.208
 * 文件修改 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传接口：
     * @RequestPart("file") - 此file要与前端文件上传组【elementUi】件的name属性值一致
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart("file")MultipartFile file){
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename(); //xxx.png
            //获取扩展名
            String exName = originalFilename.substring(originalFilename.lastIndexOf(".")+1); // png

            //调用工具类上传文件到fastDfs
            // /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String fileName = FastDfsUtils.upload(file.getBytes(), exName);
            //将文件名响应给前端
            return AjaxResult.me().setResultObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 文件删除接口
     *  /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg = path
     *  group1   M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
     * @return
     */
    //  http://localhost:8080/department/2 @PathVariable("id")
    //  http://localhost:8080/fastDfs/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg - 不行
    //  http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg -
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){
        try {
            // /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            // group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String pathTemp = path.substring(1);
            //获取组名
            String groupName = pathTemp.substring(0,pathTemp.indexOf("/"));
            //获取文件名
            String fileName = pathTemp.substring(pathTemp.indexOf("/")+1);
            System.out.println(groupName);
            System.out.println(fileName);
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
